package com.egene.tw.activity.settings.devicemanage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.egene.tw.R;
import com.egene.tw.activity.settings.devicelist.DeviceListActivity;
import com.egene.tw.activity.settings.devicelist.DeviceListActivity_;
import com.egene.tw.activity.signs.BaseMeasureActivity;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.bus.BusHelper;
import com.egene.tw.bus.ConnectStatusChangeEvent;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.entity.DeviceSetting;
import com.egene.tw.ui.signs.PowerCenterView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;

@EActivity(R.layout.activity_device_manage)
public class DeviceManageActivity extends BaseMeasureActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusHelper.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusHelper.unRegister(this);
    }

    DeviceSetting deviceSetting;

    @ViewById(R.id.viewCenter)
    PowerCenterView viewCenter;

    //ToolBar Views
    @ViewById(R.id.actionBar)
    Toolbar mToolbarView;
    @ViewById(R.id.textPower)
    TextView textPower;
    @ViewById(R.id.textConnectStatus)
    TextView textConnectStatus;
    @ViewById(R.id.imgFandDiu)
    ImageView imgFandDiu;
    @ViewById(R.id.imgRemind)
    ImageView imgRemind;
    @ViewById(R.id.imgLight)
    ImageView imgLight;
    @ViewById(R.id.imgDsMeasure)
    ImageView imgDsMeasure;

    @AfterViews
    void initViews() {
        mToolbarView.setNavigationIcon(R.drawable.ic_back);
        mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initBle();

        loadSetting();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {
            if (checkNotificationListenerEnable()) {
                if (deviceSetting == null) {
                    return;
                }
                deviceSetting.setDisremind(false);
                RealmHelper.saveSettings(deviceSetting);

                loadSetting();
            }
        }
    }


    @Click(R.id.viewConnectDevice)
    void viewConnectDevice() {
        Intent intent = new Intent(this, DeviceListActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewFindDevice)
    void viewFindDevice() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        findDevice();
    }

    @Click(R.id.viewFangDiu)
    void viewFangDiu() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        if (deviceSetting == null) {
            return;
        }
        fangDiu(!deviceSetting.isDisfangdiu());

        deviceSetting.setDisfangdiu(!deviceSetting.isDisfangdiu());
        RealmHelper.saveSettings(deviceSetting);
        loadSetting();
    }

    @Click(R.id.viewRemind)
    void viewRemind() {
//        new AlertDialog.Builder(this)
//                .setTitle("提示")
//                .setMessage("智能提醒功能需要通知使用權，請前往設置。")
//                .setPositiveButton("前往設置", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
//                        startActivityForResult(intent, 101);
//                    }
//                })
//                .setNegativeButton("取消", null)
//                .show();
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        if (deviceSetting == null) {
            return;
        }
//        if (!checkNotificationListenerEnable()) {
        if (deviceSetting.isDisremind()) {
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("智能提醒功能需要通知使用權，請前往設置。")
                    .setPositiveButton("前往設置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                            startActivityForResult(intent, 101);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        } else {
            deviceSetting.setDisremind(!deviceSetting.isDisremind());
            RealmHelper.saveSettings(deviceSetting);

            loadSetting();
        }
    }

    @Click(R.id.viewLP)
    void viewLP() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        if (deviceSetting == null) {
            return;
        }
        light(!deviceSetting.isDislight());

        deviceSetting.setDislight(!deviceSetting.isDislight());
        RealmHelper.saveSettings(deviceSetting);

        loadSetting();
    }

    @Click(R.id.viewDSCL)
    void viewDSCL() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        if (deviceSetting == null) {
            return;
        }
        dsMeasure(!deviceSetting.isDisdsMeasure());

        deviceSetting.setDisdsMeasure(!deviceSetting.isDisdsMeasure());
        RealmHelper.saveSettings(deviceSetting);

        loadSetting();
    }

    @Click(R.id.viewClearData)
    void viewClearData() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("確定清除設備與手機上的數據嗎？")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearData();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Subscribe
    public void onEvent(ConnectStatusChangeEvent data) {
        updateUI();
    }

    private void updateUI() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            textConnectStatus.setText(R.string.status_un_bind);
            textPower.setText("--");
            viewCenter.setPercent(0);
        } else if (BluetoothLeServiceV2.connected) {
            textConnectStatus.setText(R.string.status_connect);
            textPower.setText("" + BluetoothLeServiceV2.power);
            viewCenter.setPercent(BluetoothLeServiceV2.power);
        } else {
            textConnectStatus.setText(R.string.status_disconnect);
            textPower.setText("--");
            viewCenter.setPercent(0);
        }
    }

    private void loadSetting() {
        deviceSetting = RealmHelper.loadSettings();
        imgFandDiu.setImageResource(deviceSetting.isDisfangdiu() ? R.drawable.switch_off : R.drawable.switch_on);
        imgRemind.setImageResource(deviceSetting.isDisremind() ? R.drawable.switch_off : R.drawable.switch_on);
        imgLight.setImageResource(deviceSetting.isDislight() ? R.drawable.switch_off : R.drawable.switch_on);
        imgDsMeasure.setImageResource(deviceSetting.isDisdsMeasure() ? R.drawable.switch_off : R.drawable.switch_on);
    }
}
